// app.js
App({
  onLaunch() {
    wx.getStorage({
      key: 'user',
      success: res=> {
        this.globalData.userInfo = res.data
      }
    })
    wx.getStorage({
      key: 'access_token',
      success: res=> {
        this.globalData.access_token = res.data
      }
    })

    wx.login({
      success: r => {
        if(r.errMsg == 'login:ok') {
          this.requestUrl('/login', {code: r.code}, ret=> {
            this.globalData.login = ret.login
            wx.setStorage({
              key:"login",
              data:ret.login
            })
            if(ret.user != null) {
              this.globalData.userInfo = ret.user
              this.globalData.access_token = ret.access_token
              wx.setStorage({
                key:"user",
                data:ret.user
              })
              
              wx.setStorage({
                key:"access_token",
                data:ret.access_token
              })
            }
          }, 'POST')
        }
      }
    })

  },
  globalData: {
    userInfo: null,
    access_token: null,
    login: null
  },
  requestUrl(url, data, success, method = 'POST', loadding = true, header = {'content-type': 'application/json'}) {
    if(this.globalData.access_token) {
      header['Authorization'] = 'Bearer ' + this.globalData.access_token
    }
    if(loadding) wx.showLoading({
      title: '加载中',
    })
    let s = res=>{
      wx.hideLoading()
      if(res.statusCode == 200) {
        success(res.data.data)
      }else{
        if(res.statusCode ==401) {
          wx.removeStorage({
            key: 'user'
          })
          wx.removeStorage({
            key: 'access_token'
          })
          this.globalData.access_token = null
          this.globalData.userInfo = null
          wx.showToast({
            title: '登录失效，请返回首页',
            icon: 'none',
            duration: 2000
          })
        }else{
          wx.showModal({
            title: '提示',
            content: res.data.message,
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          
          // wx.showToast({
          //   title: res.data.message,
          //   icon: 'none',
          //   duration: 2000
          // }) 
        }
               
      }
      
    }
    let fail = res=>{
      console.log(res)
    }
    wx.request({
      url: 'https://diancan.api.junyi2013.com/api' + url,
      data,
      method,
      header,
      success: s
    })
  }
})
